package com.yyk.yykywd.mvvm.ui

import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.orhanobut.logger.Logger
import com.yyk.yykywd.*
import com.yyk.yykywd.bean.BaseBean
import com.yyk.yykywd.listenter.DialogSureCancelListenter
import com.yyk.yykywd.mvvm.adapter.AddMaterialAdapter
import com.yyk.yykywd.mvvm.base.BaseTakePhotoActivity
import com.yyk.yykywd.mvvm.entity.UploadBean
import com.yyk.yykywd.mvvm.event.FinishWorkDetail
import com.yyk.yykywd.mvvm.view_model.AddPictureViewModel
import com.yyk.yykywd.util.DensityUtils
import com.yyk.yykywd.util.DialogUtil
import com.yyk.yykywd.util.ToastUtil
import com.yyk.yykywd.util.UploadUtil
import com.yyk.yykywd.widght.SpaceItemDecoration
import kotlinx.android.synthetic.main.activity_agent_refund.*
import kotlinx.android.synthetic.main.rl_bottom.*
import org.devio.takephoto.model.TResult
import org.greenrobot.eventbus.EventBus

class AgentRefundActivity : BaseTakePhotoActivity() {
    private lateinit var apply_adapter: AddMaterialAdapter
    private lateinit var confirmation_adapter: AddMaterialAdapter
    private lateinit var viewModel: AddPictureViewModel

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val result = msg.obj as String
            val gson = Gson()
            val info: UploadBean = gson.fromJson(result, UploadBean::class.java)
            if (info.code != 1) {
                ToastUtil.showShort(mActivity, info.msg)
                return
            }

            when (viewModel.type) {
                FROM_REFUND_APPLY -> {
                    viewModel.refundForm.add(info.data)
                    apply_adapter.notifyDataSetChanged()
                }
                FROM_REFUND_CONFIRMATION -> {
                    viewModel.refundConfirmationForm.add(info.data)
                    confirmation_adapter.notifyDataSetChanged()
                }
            }
        }
    }

    override fun initData() {
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_agent_refund
    }

    override fun initView() {
        setBackArrow {
            backAndDelImg()
        }
        setTitle("代理商退款")

        viewModel = getViewModel(this, AddPictureViewModel::class.java)
        viewModel.id = intent.getStringExtra(ID)
        viewModel.pact_id = intent.getStringExtra(PACT_ID)
        viewModel.money = intent.getStringExtra(MONEY)
        viewModel.name = intent.getStringExtra(NAME)
        viewModel.refund_num = intent.getIntExtra(REFUND_NUM, 0)
        viewModel.back_money_num = intent.getIntExtra(BACK_MONEY_NUM, 0)

        rv_refund_apply_form.layoutManager = GridLayoutManager(mActivity, 4)
        rv_refund_apply_form.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        apply_adapter = AddMaterialAdapter(mActivity, viewModel.refundForm)
        apply_adapter.maxImages = AddMaterialActivity.MAX_IMAGES
        rv_refund_apply_form.adapter = apply_adapter

        rv_refund_confirmation.layoutManager = GridLayoutManager(mActivity, 4)
        rv_refund_confirmation.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        confirmation_adapter = AddMaterialAdapter(mActivity, viewModel.refundConfirmationForm)
        confirmation_adapter.maxImages = AddMaterialActivity.MAX_IMAGES
        rv_refund_confirmation.adapter = confirmation_adapter

        tv_amount_received.text = "已回款金额：" + viewModel.money + "元"
        tv_agent_site_name.text = "代理站点名称：" + viewModel.name
    }

    override fun takeSuccess(result: TResult) {
        Logger.e(UploadUtil.TAG + result.image.compressPath)
        viewModel.uploadContractImg(CONTRACT, result.image.compressPath)
    }

    override fun setListener() {
        super.setListener()
        tv_execute.setOnClickListener {
            if (viewModel.refundForm.size == 0) {
                ToastUtil.showShort("请上传退款申请表")
                return@setOnClickListener
            }
            if (viewModel.refundConfirmationForm.size == 0) {
                ToastUtil.showShort("请上传退款确认表")
                return@setOnClickListener
            }
            if (getTextString(et_refund_reason).isBlank()) {
                ToastUtil.showShort("请填写退款原因")
                return@setOnClickListener
            }
            val message: String = if (viewModel.refund_num == 1) {
                "退款后此客户将自动进入公海客户，若需继续跟进，请到公海中拾起此客户"
            } else {
                if (viewModel.back_money_num == 1) {
                    "退款后此客户将自动进入回款完成，您可在\"全款合同列表\"中查看此项业务"
                } else {
                    "代理站点：" + viewModel.name
                }
            }
            submitRefund(mActivity, message) {
                viewModel.refund(getTextString(et_refund_reason), getTextString(et_refund_note))
            }
        }

        setAdapterChildClickListener(mActivity, apply_adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {
                viewModel.type = FROM_REFUND_APPLY
            }

            override fun clickRemove(position: Int) {
                viewModel.delSingleOrMulti = SINGLE
                viewModel.del_type = FROM_REFUND_APPLY
                viewModel.del_position = position
                viewModel.removeImg(viewModel.refundForm[position])
            }

        })
        setAdapterChildClickListener(mActivity, confirmation_adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {
                viewModel.type = FROM_REFUND_CONFIRMATION
            }

            override fun clickRemove(position: Int) {
                viewModel.delSingleOrMulti = SINGLE
                viewModel.del_type = FROM_REFUND_CONFIRMATION
                viewModel.del_position = position
                viewModel.removeImg(viewModel.refundConfirmationForm[position])
            }

        })

        viewModel.responseMessage.observe(this, Observer<String> { t ->
            val msg = Message.obtain()
            msg.what = 1
            msg.obj = t
            handler.sendMessage(msg)
        })

        viewModel.delSuccess.observe(this, Observer<BaseBean> {
            if (it.code != 200) {
                ToastUtil.showShort(it.msg)
                return@Observer
            }
            if (viewModel.delSingleOrMulti == MULTI) {
                finish()
                return@Observer
            }
            when (viewModel.del_type) {
                FROM_REFUND_APPLY -> {
                    viewModel.refundForm.removeAt(viewModel.del_position)
                    apply_adapter.notifyDataSetChanged()
                }
                FROM_REFUND_CONFIRMATION -> {
                    viewModel.refundConfirmationForm.removeAt(viewModel.del_position)
                    confirmation_adapter.notifyDataSetChanged()
                }
            }
        })

        viewModel.refundInfo.observe(this, Observer<BaseBean> {
            ToastUtil.showShort(it.msg)
            if (it.code == 200) {
                if (viewModel.refund_num == 1) {
                    EventBus.getDefault().post(FinishWorkDetail())
                }
                finish()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backAndDelImg()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun backAndDelImg() {
        val list = viewModel.refundConfirmationForm + viewModel.refundForm
        if (list.isNotEmpty()) {
            viewModel.delSingleOrMulti = MULTI
            viewModel.removeImg(listToString(list as MutableList<String>))
        } else {
            finish()
        }
    }
}
